//
//  QRCodeViewController.swift
//  WBDemo
//
//  Created by Jin on 19/04/2018.
//  Copyright © 2018 com.baidu.123. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController {

    @IBOutlet weak var customTabbar:UITabBar?
    @IBOutlet weak var customContainView:UIView!
    @IBOutlet weak var scanLine:UIImageView!
    @IBOutlet weak var containHeightCons:NSLayoutConstraint!
    @IBOutlet weak var scanLineTopCons:NSLayoutConstraint!
    
    // MARK: - 视图声明周期
    override func viewDidLoad() {
        super.viewDidLoad()
        
        customTabbar?.selectedItem = customTabbar?.items![0]
        customTabbar?.delegate = self
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        startAnimation()
        
        //开始扫描
        startScan()
    }

    // MARK: - 内部控制方法
    @IBAction func closeBtnClick(sender:UIBarButtonItem){
        dismiss(animated: true, completion: nil)
    }
    
    @IBAction func photoBtnClick(sender:UIBarButtonItem){
        
        guard UIImagePickerController.isSourceTypeAvailable(.photoLibrary) else {
            return
        }
        
        let picker = UIImagePickerController()
        picker.delegate = self
        present(picker, animated: true, completion: nil)
    }

    //开始扫描动画
    private func startAnimation(){
        scanLineTopCons.constant = -containHeightCons.constant
        view.layoutIfNeeded()
        
        UIView.animate(withDuration: 1.0) {
            UIView.setAnimationRepeatCount(MAXFLOAT)
            self.scanLineTopCons.constant = self.containHeightCons.constant
            self.view.layoutIfNeeded()
        }
    }
    
    //执行扫描
    private func startScan(){
        if !session.canAddInput(input!) {
            return
        }
        if !session.canAddOutput(output){
            return
        }
        session.addInput(input!)
        session.addOutput(output)
        output.metadataObjectTypes = output.availableMetadataObjectTypes
        output.setMetadataObjectsDelegate(self as AVCaptureMetadataOutputObjectsDelegate, queue: DispatchQueue.main)
        view.layer.insertSublayer(previewLayer, at: 0)
        view.layer.insertSublayer(drawLayer, above: previewLayer)
        session.startRunning()
    }
    
    // MARK: - 懒加载
    //创建输入
    private lazy var input:AVCaptureDeviceInput? = {
        let device = AVCaptureDevice.default(for: .video)
        guard let deviceInput = try? AVCaptureDeviceInput(device: device!) else {
            return nil
        }
        
        return deviceInput
    }()
    //创建输出
    private lazy var output:AVCaptureMetadataOutput = {
        let out = AVCaptureMetadataOutput()
        //注意:该属性接收的不是坐标而是比例
        let rect = self.view.bounds
        let containerRect = self.customContainView.frame
        out.rectOfInterest = CGRect(x: containerRect.origin.y / rect.size.height, y: containerRect.origin.x / rect.size.width, width: containerRect.size.height / rect.size.height, height: containerRect.size.width / rect.size.width)
        return out
    }()
    //创建会话
    private lazy var session:AVCaptureSession = AVCaptureSession()
    //创建预览图层
    private lazy var previewLayer:AVCaptureVideoPreviewLayer = {
        let layer = AVCaptureVideoPreviewLayer(session: self.session)
        layer.frame = self.view.bounds
        return layer
    }()
    
    //创建保存二维码边线的图层
    private lazy var drawLayer:CALayer = {
        let layer = CALayer()
        layer.frame = self.view.bounds
        return layer
    }()
}

extension QRCodeViewController:UITabBarDelegate{
    func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        //1.修改容器高度
        containHeightCons.constant = (item.tag == 0) ? 300 : 150
        //2.停止动画
        scanLine.layer.removeAllAnimations()
        //3.开始动画
        startAnimation()
    }
}

extension QRCodeViewController:AVCaptureMetadataOutputObjectsDelegate {
    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
        
        cleanLines()
        
        for objc in metadataObjects as! [AVMetadataMachineReadableCodeObject] {
            let res = previewLayer.transformedMetadataObject(for: objc)
            
            
            drawLindes(res as? AVMetadataMachineReadableCodeObject)
        }
    }
    
    private func drawLindes(_ cornersObjc:AVMetadataMachineReadableCodeObject?){
        
        guard let corners = cornersObjc?.corners else {
            JLog(message: "没有数据")
            return
        }
    
        
        let shapeLayer = CAShapeLayer()
        shapeLayer.strokeColor = UIColor.orange.cgColor
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.lineWidth = 4
        
        let path = UIBezierPath()
        path.move(to: corners.first!)
        for tempPoint in corners {
            path.addLine(to: tempPoint)
        }
        
        path.close()
        
        shapeLayer.path = path.cgPath
        drawLayer.addSublayer(shapeLayer)
    }
    
    //清空二维码边线
    private func cleanLines(){
        guard let subLayers = drawLayer.sublayers else {
            return
        }
        
        for layer in subLayers {
            layer.removeFromSuperlayer()
        }
    }
}

extension QRCodeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else {
            return
        }
        
        let ciImage = CIImage(image: image)
        let dict = [CIDetectorAccuracy:CIDetectorAccuracyHigh]
        let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: dict)
        let features = detector?.features(in: ciImage!)
        for objc in features! {
            JLog(message: (objc as! CIQRCodeFeature).messageString)
        }
        
        picker.dismiss(animated: true, completion: nil)
    }
}
